<?php

class Login
{
    const NAME_FIELD = 'name';
    const PASSWORD_FIELD = 'password';
    
    protected $_username;
    protected $_password;
    
    protected $_Session;
    /**
     * @var DatabaseConnection
     */
    protected $_DB;
    
    public function __construct($username, $password)
    {
        if (!Validator::isName($username)) {
            throw new InvalidArgumentException('Invalid name');
        }
        $this->_username = $username;
        if (!Validator::isNotEmpty($password)) {
            throw new InvalidArgumentException('No password given');
        }
        $this->_password = (string) $password;
        
        $Session = Session::getInstance();
        if (!isset($Session['login'])) {
            $Session['login'] = array();
        }
        $this->_Session =& $Session['login'];
        $this->_DB = DB::getInstance()->getPrimary();
    }
    
    public function doLogin()
    {
        $sql = sprintf("SELECT u.id, u.name, COUNT(*) AS isValid FROM ?pre%s AS u WHERE %s = '%s' AND %s = '%s'",
				USER::TABLE,
				self::NAME_FIELD,
				$this->_DB->escape($this->username),
				self::PASSWORD_FIELD,
				$this->_DB->escape(encryptPassword($this->password))
			);
		$user = $this->_DB->getOne($sql);
		if ($user['isValid'] != 1) {
			sleep(5);
			return false;
		}
		$this->_Session['OK'] = true;
		$this->_Session['id'] = $user['id'];
		$this->_Session['name'] = $user[self::NAME_FIELD];
		return true;
    }
    
    public function doLogout()
    {
		$this->_Session['OK'] = false;
		return true;
    }
}

class LoginException extends PhlameException
{}